// pages/user/addAddress/addAddress.js
Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		isChooseCity: false,
		addressId: 0,
		info: {
			region: ["北京市", "北京市", "东城区"]
		},
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function(options) {
		if (options.id) {
			wx.setNavigationBarTitle({
				title: "更新地址"
			});
			this.data.addressId = options.id;
			this.loadInfo();
		} else {
			wx.setNavigationBarTitle({
				title: "添加地址"
			});
		}
	},

	// 地区选择
	regionChange: function(e) {
		this.setData({
			'info.region': e.detail.value
		});
	},

	// 获取地址信息
	loadInfo: function() {
		wx.http.post('api/address/detail', {
			address_id: this.data.addressId
		}, {showLoading: true}).then((res) => {
			res = res.data.data;
			const info = res.detail;
			info.region = res.region;
			this.setData({info: info});
		});
	},

	// 保存并返回上一页
	onSubmit: function(e) {
		const values = e.detail.value;
		const url = this.data.addressId ? 'api/address/edit' : 'api/address/add';
		if (this.data.addressId) values.address_id = this.data.addressId;
		values.region = this.data.info.region.join(",");

		return wx.http.post(url, values).then((res) => {
			wx.emitter.emit('address.update');
			wx.navigateBack({
				delta: 1
			});
		});
	},
});
